import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/net/base_entity.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/util/device_utils.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/iview/file_upload_iview.dart';
import 'package:flutter_deer/widgets/presenter/file_upload_presenter.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http_parser/src/media_type.dart';

class SelectedImage extends StatefulWidget {

  const SelectedImage({
    super.key,
    this.url,
    this.heroTag,
    this.size = 80.0,
  });

  final String? url;
  final String? heroTag;
  final double size;

  @override
  SelectedImageState createState() => SelectedImageState();
}

class SelectedImageState extends State<SelectedImage> with BasePageMixin<SelectedImage, PowerPresenter<dynamic>> implements FileUploadIMvpView {

  final ImagePicker _picker = ImagePicker();
  ImageProvider? _imageProvider;
  XFile? pickedFile;

  late FileUploadPagePresenter fileUploadPagePresenter;

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    fileUploadPagePresenter = new FileUploadPagePresenter();
    powerPresenter.requestPresenter([fileUploadPagePresenter]);
    return powerPresenter;
  }

  @override
  void uploadResult(FileUploadEntity? uploadResult){
    if(uploadResult!.url.nullSafe.isNotEmpty){
      SpUtil.putString(Constant.tempUserAvatarUrl, uploadResult!.url.nullSafe);
    }
  }

  Future<void> _getImage() async {
    try {
      pickedFile = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 800);
      if (pickedFile != null) {
        if (Device.isWeb) {
          _imageProvider = NetworkImage(pickedFile!.path);
          // fileUploadPagePresenter.uploadFile(pickedFile!.path,pickedFile!.mimeType.nullSafe);
          Uint8List list = await pickedFile!.readAsBytes();
          MultipartFile multipartFile = MultipartFile.fromBytes(list.toList(),
            filename: pickedFile!.name,
            contentType: MediaType('image', 'jpg'),
          );
          fileUploadPagePresenter.uploadWebFile(multipartFile);
        } else {
          _imageProvider = FileImage(File(pickedFile!.path));
          fileUploadPagePresenter.uploadFile(pickedFile!.path,pickedFile!.mimeType.nullSafe);
        }
      } else {
        _imageProvider = null;
      }
      setState(() {

      });
    } catch (e) {
      if (e is MissingPluginException) {
        Toast.show('${DeerLocalizations.of(context)!.platformNotSupported.nullSafe}');
      } else {
        Toast.show('${DeerLocalizations.of(context)!.noPhotoAlbumPermissions.nullSafe}');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final ColorFilter colorFilter = ColorFilter.mode(
        ThemeUtils.isDark(context) ? Colours.dark_unselected_item_color : Colours.text_gray,
        BlendMode.srcIn
    );

    Widget image = Container(
      width: widget.size,
      height: widget.size,
      decoration: BoxDecoration(
        // 图片圆角展示
        borderRadius: BorderRadius.circular(16.0),
        image: DecorationImage(
            image: _imageProvider ?? ImageUtils.getImageProvider(widget.url, holderImg: 'store/icon_zj'),
            fit: BoxFit.cover,
            colorFilter: _imageProvider == null && TextUtil.isEmpty(widget.url) ? colorFilter : null
        ),
      ),
    );

    if (widget.heroTag != null && !Device.isWeb) {
      image = Hero(tag: widget.heroTag!, child: image);
    }

    return Semantics(
      label: '${DeerLocalizations.of(context)!.selectPicture.nullSafe}',
      hint: '${DeerLocalizations.of(context)!.jumpAlbum.nullSafe}',
      child: InkWell(
        borderRadius: BorderRadius.circular(16.0),
        onTap: _getImage,
        child: image,
      ),
    );
  }
}
